import socket
import re


def grabber(host):
	ip = socket.gethostbyname(host)

	res = ""
	res += str(trygrab80(ip))
	res += "\n" + str(trygrabSSH(ip))
	res += "\n" + str(trygrabIIS(ip))
	
	return res

#IIS(microsoft.com)	
def trygrabIIS(ip):
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(4)
	
	res = ""
	
	try:
		s.connect( (ip, 80) )
		s.send("test\r\n\r\n")
		resp = s.recv(1024)
	
		if "Microsoft-HTTPAPI" in resp:
			e = re.compile('.*Microsoft-HTTPAPI.*')
			res = "Microsoft Windows, IIS: " + e.findall(resp)[0]
		else:
			res = "Parece que no es IIS"
	except socket.error as msg:
		res = "Parece que el 80 esta cerrado. Error: ", msg
	finally:
		s.close()
		
	return res
	

#OpenSSH(ogame.org)
def trygrabSSH(ip):
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(4)
	
	res = ""
	
	try:
		s.connect( (ip, 22) )
		resp = s.recv(1024)
	
		if "OpenSSH" in resp:
			e = re.compile('.*OpenSSH.*')
			res = e.findall(resp)[0]
		else:
			res = "Parece que no es OpenSSH"
	except socket.error as msg:
		res = "Parece que el 22 esta cerrado. Error: ", msg
	finally:
		s.close()
		
	return res
	
#Apache (dc.uba.ar)
def trygrab80(ip):
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(4)
	
	res = ""
	
	try:
		s.connect( (ip, 80) )
	
		s.send("test\r\n\r\n")
		resp = s.recv(1024)
	
		if "Apache" in resp:
			e = re.compile('>.*Apache.*<')
			res = e.findall(resp)[0]
		else:
			res = "Parece que no es Apache"
	except socket.error as msg:
		res = "Parece que el 80 esta cerrado. Error: ", msg
	finally:
		s.close()
		
	return res
